
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.sql.Statement;
//import java.sql.PreparedStatement;

public class HsqldbConn {
	
	Connection conn; 
   
	//Constructor, to initialize a Connection use Hsqldb-Driver
    public HsqldbConn() throws SQLException {
		try {
			Class.forName("org.hsqldb.jdbc.JDBCDriver" );
		} catch (Exception e) {
			System.err.println("ERROR: failed to load HSQLDB-JDBC driver.");
			//e.printStackTrace();
			return;
		}
		conn=null;
	}
    
    //open the connection and refer the conn to "my" database in Hsqldb
    public void openConn(String prefix){
		try{
			conn = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/"+prefix, "SA", "");		    
		}
	    catch ( SQLException e )  {       
	    	e.printStackTrace();     
	    } 
	}
    
    //simple getter
    public Connection getConn(){
    	return this.conn;
    }
  
    //close current connection
    public void closeConn() throws SQLException {   
        //Statement stat = conn.createStatement();   
    	//stat.execute("SHUTDOWN");   
    	conn.close();  
    }

    //method for update/delete/insert action to db
    public synchronized void update(String expression) throws SQLException {
        Statement st = null;
        st = conn.createStatement();    // statements
        int i = st.executeUpdate(expression);    // run the query
        if (i == -1) {
            System.out.println("db error : " + expression);
        }
        st.close();
    } 
    
    //method for select a table from database
    public ResultSet select(String expression) throws SQLException{
	    Statement stmt = this.conn.createStatement();                
	    String sql = "SELECT * From "+expression;       
	    ResultSet rs = stmt.executeQuery(sql);
	    stmt.close(); 
	    return rs;
    }
 
    
/*    public static void main(String[] args) throws SQLException     
    {         
    	HsqldbConn con = new HsqldbConn(); 
    	con.openConn("YKK");
    	Connection co=con.getConn();
    	
    	con.update("INSERT INTO Invoice(InvoiceDate) VALUES ('2011-03-21')");
        
    	ResultSet rs = con.select("SELECT * From Invoice");
	    while ( rs.next() )       
	    {     String id =  null;    
	    	  id = rs.getString(1); 
	    	  String datum = null;
	    	  datum = rs.getString(2);  
	    	  if(datum==null) datum="N/A";
	    	  System.out.println(id + ", " + datum );       
	    } 
	    rs.close(); 
    	System.out.println("Test Erfolgreich!" );
    	con.closeConn();
    }*/
}
